/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.exceptions.EdiParamException;
import com.edi.proxy.EdiParamProxy;

/**
 * 响应普通页面请求
 * 
 * @author 红木
 * 
 */
public class CommonController extends HttpServlet {

	private static final Log log = LogFactory.getLog(CommonController.class);

	private static final long serialVersionUID = 8552972821003182054L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		log.debug(" enter CommonController doGet");

		String ediParam = request.getParameter("ediPara"); // 获得ediPara，表明为客户端		

		log.debug("CommonController ,url : " + request.getRequestURL());

		EdiParamProxy ediParamProxy = null;
		try {

			ediParam = new String(ediParam.getBytes("ISO8859-1"), "UTF-8");
			log.debug("request xml : " + ediParam);
			ediParamProxy = new EdiParamProxy(ediParam);
			ediParamProxy.process();

			String answerXML = ediParamProxy.getAnswerXml();
			log.debug("return answer : " + answerXML);
			response.setHeader("Cache-Control", "no-cache");
			response.addHeader("content-type", "text/xml; charset=UTF8");
			response.getWriter().print(answerXML);

		} catch (Exception e) {
			if (ediParamProxy != null) {
				try {
					response.getWriter().print(ediParamProxy.getAnswerXml());
				} catch (EdiParamException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			log.debug(e);
			e.printStackTrace();
		}
		return;

		//
		// Enumeration en = request.getParameterNames();
		// while (en.hasMoreElements()) {
		// log.debug("param name is :" + en.nextElement());
		// }

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		doGet(request, response);
	}

}
